/**
 * Created by kevin on 2017/6/4.
 */
var model= require('./model');

var Robots = model.createModel({
    name : String,
    token : String,
    ctime : {type : Date,default:Date.now}
},'Robots');

Robots.getAll = function(callback) {
    Robots.find({},null,{ lean: true ,sort:{ctime:-1}},callback);
}

Robots.getById = function (id,callback) {
    Robots.findById(id,callback);
}

Robots.createUnique = function (doc,callback) {
    Robots.findOne({"$or":[{'name':doc.name},{'token':doc.token}]},function (err,robot) {
        if (robot) {
            if (callback) {
                if (robot.name === doc.name) {
                    callback(new Error('该名字已被占用',null));
                } else  {
                    callback(new Error('该机器人已经存在',null));
                }
            }
        } else  {
            Robots.create(doc,callback);
        }
    });
}

Robots.edit = function (id,doc,callback) {
    Robots.findByIdAndUpdate(id, doc, callback);
}

module.exports= Robots;